package com.patrol.logisticsmanage.ui.canteen;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.patrol.logisticsmanage.R;
import com.patrol.logisticsmanage.common.AndroidBug5497Workaround;
import com.patrol.logisticsmanage.net.BaseObserver;
import com.patrol.logisticsmanage.net.BaseReponse;
import com.patrol.logisticsmanage.net.BaseRequest;
import com.patrol.logisticsmanage.ui.appear.model.Canteen;
import com.patrol.logisticsmanage.ui.appear.model.SubCamp;
import com.patrol.logisticsmanage.ui.base.BaseActivity;
import com.patrol.logisticsmanage.ui.base.PickerDialog;
import com.patrol.logisticsmanage.ui.canteen.bean.CanteenListInfo;
import com.patrol.logisticsmanage.ui.canteen.bean.Restaurant;
import com.patrol.logisticsmanage.ui.canteen.utils.GsonUtil;
import com.patrol.logisticsmanage.ui.canteen.utils.LogUtils;
import com.patrol.logisticsmanage.ui.canteen.utils.ToastUtils;

import org.jaaksi.pickerview.dataset.OptionDataSet;
import org.jaaksi.pickerview.dialog.OnPickerChooseListener;
import org.jaaksi.pickerview.picker.BasePicker;
import org.jaaksi.pickerview.picker.OptionPicker;
import org.jaaksi.pickerview.util.Util;
import org.jaaksi.pickerview.widget.DefaultCenterDecoration;
import org.jaaksi.pickerview.widget.PickerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

@Route(path = "/app/CanteenActivity")
public class CanteenActivity extends BaseActivity implements CanteenAdapter.OnItemClick, OptionPicker.OnOptionSelectListener{

    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.rcy_canteen)
    RecyclerView rcyCanteen;

    CanteenAdapter canteenAdapter;
    List<Restaurant> restaurants;
    //地址选择器
    private OptionPicker mPicker;
    DefaultCenterDecoration decoration;
    List<SubCamp> subCampList;

    @Autowired
    boolean isCanOrder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_canteen);
        ButterKnife.bind(this);
        AndroidBug5497Workaround.assistActivity(this);

        initAddressPickerView();
        rcyCanteen.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));

        restaurants = new ArrayList<>();
        canteenAdapter = new CanteenAdapter(mContext, restaurants, this);
        rcyCanteen.setAdapter(canteenAdapter);

        subCampList = new ArrayList<>();
        getAddressData();
        String shitId = "";
        if(isCanOrder){
            shitId = "1340587619879288834";
        }else{
            tvAddress.setVisibility(View.VISIBLE);
        }
        getData(shitId);
    }

    private void initAddressPickerView() {
        // 设置CenterDecoration
        decoration = new DefaultCenterDecoration(mContext);
        decoration
                .setLineColor(Color.parseColor("#dd199475"))
//                .setDrawable(Color.parseColor("#199475"))
                //.setDrawable(Color.parseColor("#999999"))
                .setLineWidth(1)
                .setMargin(Util.dip2px(mContext, 10), Util.dip2px(mContext, -3), Util.dip2px(mContext, 10),
                        Util.dip2px(mContext, -3));
        mPicker =
                new OptionPicker.Builder(mContext, 2, this)
                        .dialog(new PickerDialog())
                        .setInterceptor(new BasePicker.Interceptor() {
                            @Override
                            public void intercept(PickerView pickerView, LinearLayout.LayoutParams params) {
                                int level = (int) pickerView.getTag();
                                pickerView.setVisibleItemCount(3);
                                // setInterceptor 可以根据level区分设置pickerview属性
                                pickerView.setCenterDecoration(decoration);
                                pickerView.setTextSize(15, 20);
                                pickerView.setColor(Color.parseColor("#199475"), Color.parseColor("#444444"));
                            }
                        }).create();
        PickerDialog pickerDialog = (PickerDialog) mPicker.dialog();
        Dialog dialog = pickerDialog.getDialog();

        //DefaultPickerDialog dialog = (DefaultPickerDialog) mPicker.dialog();
        pickerDialog.getTitleView().setText("请选择营区食堂");
        // 设置弹窗
        dialog.setCanceledOnTouchOutside(true);
        dialog.getWindow().setGravity(Gravity.BOTTOM);

        // 拦截缺点按钮的事件
        pickerDialog.setOnPickerChooseListener(new OnPickerChooseListener() {
            @Override
            public boolean onConfirm() {
                SubCamp subCamp = subCampList.get(mPicker.getSelectedPosition()[0]);
                Canteen canteen = subCamp.getCanteens().get(mPicker.getSelectedPosition()[1]);
                tvAddress.setText(subCamp.getTitle() + " " + canteen.getName());
                getData(canteen.getId());
                dialog.dismiss();
                // 返回false表示拦截
                return false;
            }

            @Override
            public void onCancel() {
            }
        });

        mPicker.setData(subCampList);
    }

    @OnClick(R.id.tv_address)
    public void onViewClicked() {
        mPicker.show();
    }

    private void getData(String shitId) {
        LogUtils.e("----------" + shitId);
        BaseRequest.getInstance().getApiServise().getList(shitId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Map>(mContext) {
                    @Override
                    public void onSuccess(BaseReponse<Map> baseReponse) {
                        Map map = baseReponse.getResults();
                        List records = (List) map.get("records");
                        List<Restaurant> list = GsonUtil.mapListToBeanList(records, Restaurant.class);
                        LogUtils.e("******" + list);
                        restaurants.clear();
                        restaurants.addAll(list);
                        canteenAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
//                        if (tBaseReponse.getCode()==500){
//                            ToastUtils.showToast(tBaseReponse.getMessage());
//                            AppConfig.putString("token","");
//                            ARouter.getInstance().build("/app/login").navigation();
//                        }
                    }

                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {

                    }
                });
    }

    private void getAddressData() {
        BaseRequest.getInstance().getApiServise().getSubCampList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List>(mContext) {
                    @Override
                    public void onSuccess(BaseReponse<List> baseReponse) {
                        List result = baseReponse.getResults();
                        List<SubCamp> list = GsonUtil.mapListToBeanList(result, SubCamp.class);
                        subCampList.clear();
                        subCampList.addAll(list);
                        getCanteenData();
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) { }
                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception { }
                });
    }

    private void getCanteenData() {
        BaseRequest.getInstance().getApiServise().getAllCanteenList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List<CanteenListInfo>>(mContext) {
                    @Override
                    public void onSuccess(BaseReponse<List<CanteenListInfo>> baseReponse) {
                        List<CanteenListInfo> results = baseReponse.getResults();
                        for (int i=0;i<subCampList.size();i++){
                            for (int j=0;j<results.size();j++){
                                CanteenListInfo canteenListInfo = results.get(j);
                                if (canteenListInfo.getYingquId().equals(subCampList.get(i).getValue())){
                                    subCampList.get(i).setCanteens(canteenListInfo.getShitList());
                                    results.remove(j);
                                    break;
                                }
                            }
                        }
                        mPicker.setData(subCampList);
                    }

                    @Override
                    public void onCodeError(BaseReponse tBaseReponse) {
//                        if (tBaseReponse.getCode()==500){
//                            ToastUtils.showToast(tBaseReponse.getMessage());
//                            AppConfig.putString("token","");
//                            ARouter.getInstance().build("/app/login").navigation();
//                        }
                    }

                    @Override
                    public void onFailure(Throwable e, boolean netWork) throws Exception {

                    }
                });
    }

    @Override
    public void onOptionSelect(OptionPicker picker, int[] selectedPosition, OptionDataSet[] selectedOptions) {

        ToastUtils.showToast(selectedPosition[0]+"~"+selectedPosition[1]);
    }

    @Override
    public void onClick(int position) {
        ARouter.getInstance().build("/app/canteenDetail")
                .withBoolean("isCanOrder",isCanOrder)
                .withString("restaurantString", GsonUtil.objectToGson(restaurants.get(position))).navigation();
    }
}
